import React, { Reducer, useReducer } from 'react';

interface ActionsProps {
    type: 'add' | 'sub';
    num: number,
}

const testReducer: Reducer<number, ActionsProps> = (state: number, action: ActionsProps): number => {
    switch (action.type) {
        case 'add':
            return state + action.num;
        case 'sub':
            return state - action.num;
        default:
            // 如果所有分支都有对应的 case,则default时，action.type被收缩为 never 类型，这里不会报错
            // 当增加 type 的类型后如果这里没有与之匹配的分支就会提示报错，减少代码隐患
            const n: never = action.type;
            console.log(n);
            return state;
    }
};

const initialState = 0;
export default () => {
    const [test, dispatch] = useReducer<Reducer<number, ActionsProps>>(testReducer, initialState);
    return (
        <div>
            <p>{ test }</p>
            <button onClick={ () => {
                dispatch({
                    type: 'add',
                    num: 1,
                });
            } }>加
            </button>
            <button onClick={ () => {
                dispatch({
                    type: 'sub',
                    num: 2,
                });
            } }>减
            </button>
        </div>
    );
}